{% extends 'base.html' %}

{% block title %}{% if contract %}编辑合同{% else %}新增合同{% endif %} - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
.file-upload-area {
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    padding: 30px;
    text-align: center;
    background-color: #f8f9fa;
    transition: all 0.3s ease;
    cursor: pointer;
}

.file-upload-area:hover {
    border-color: #007bff;
    background-color: #e3f2fd;
}

.file-upload-area.dragover {
    border-color: #007bff;
    background-color: #e3f2fd;
    transform: scale(1.02);
}

.file-item {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 12px;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.file-info {
    display: flex;
    align-items: center;
    flex-grow: 1;
}

.file-icon {
    font-size: 1.5rem;
    margin-right: 12px;
    width: 30px;
    text-align: center;
}

.file-details h6 {
    margin: 0;
    font-size: 0.9rem;
}

.file-details small {
    color: #6c757d;
}

.btn-remove-file {
    background: none;
    border: none;
    color: #dc3545;
    font-size: 1.1rem;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 4px;
    transition: background-color 0.2s;
}

.btn-remove-file:hover {
    background-color: #f5c6cb;
}

.form-section {
    background: #fff;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.form-section h5 {
    color: #495057;
    border-bottom: 2px solid #007bff;
    padding-bottom: 8px;
    margin-bottom: 20px;
}

.required-field::after {
    content: " *";
    color: #dc3545;
}

.status-badge {
    display: inline-block;
    padding: 8px 16px;
    border-radius: 20px;
    font-weight: 600;
    text-align: center;
    margin-bottom: 15px;
}

.status-draft {
    background: #f8f9fa;
    color: #6c757d;
    border: 2px solid #dee2e6;
}

.status-active {
    background: #d4edda;
    color: #155724;
    border: 2px solid #28a745;
}

.review-timeline {
    position: relative;
    padding-left: 30px;
}

.review-timeline::before {
    content: '';
    position: absolute;
    left: 15px;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #dee2e6;
}

.review-item {
    position: relative;
    margin-bottom: 20px;
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    border-left: 4px solid #007bff;
}

.review-item::before {
    content: '';
    position: absolute;
    left: -23px;
    top: 20px;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #007bff;
    border: 3px solid #fff;
}
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
                <li class="breadcrumb-item"><a href="{% url 'assets:contract_list' %}">合同管理</a></li>
                <li class="breadcrumb-item active" aria-current="page">{% if contract %}编辑合同{% else %}新增合同{% endif %}</li>
            </ol>
        </nav>
        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-file-contract me-2"></i>{% if contract %}编辑合同{% else %}新增合同{% endif %}</h2>
            <div class="btn-group">
                <a href="{% url 'assets:contract_list' %}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i>返回列表
                </a>
                {% if contract %}
                <a href="{% url 'assets:contract_detail' contract.pk %}" class="btn btn-outline-info">
                    <i class="fas fa-eye me-1"></i>查看详情
                </a>
                {% endif %}
            </div>
        </div>

        <form method="post" enctype="multipart/form-data" id="contractForm">
    {% csrf_token %}

    {% if contract_form.errors %}
    <div class="alert alert-danger" role="alert">
        请修正以下错误：
        <ul>
            {% for field in contract_form %}
                {% if field.errors %}
                    {% for error in field.errors %}
                        <li>{{ field.label }}: {{ error }}</li>
                    {% endfor %}
                {% endif %}
            {% endfor %}
            {% for error in contract_form.non_field_errors %}
                <li>{{ error }}</li>
            {% endfor %}
        </ul>
    </div>
    {% endif %}

    <!-- 合同基本信息 -->
    <div class="form-section">
        <h5><i class="fas fa-info-circle me-2"></i>合同基本信息</h5>
        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ contract_form.name.id_for_label }}" class="form-label required-field">合同名称</label>
                    {{ contract_form.name }}
                    {% if contract_form.name.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.name.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ contract_form.contract_number.id_for_label }}" class="form-label required-field">合同编号</label>
                    {{ contract_form.contract_number }}
                    {% if contract_form.contract_number.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.contract_number.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ contract_form.contract_type.id_for_label }}" class="form-label">合同类型</label>
                    {{ contract_form.contract_type }}
                    {% if contract_form.contract_type.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.contract_type.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ contract_form.supplier.id_for_label }}" class="form-label required-field">关联供应商</label>
                    {{ contract_form.supplier }}
                    {% if contract_form.supplier.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.supplier.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>
    </div>
    
    <!-- 合同期限与金额 -->
    <div class="form-section">
        <h5><i class="fas fa-calendar-alt me-2"></i>合同期限与金额</h5>
        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ contract_form.signed_date.id_for_label }}" class="form-label">签订日期</label>
                    {{ contract_form.signed_date }}
                    {% if contract_form.signed_date.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.signed_date.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ contract_form.effective_date.id_for_label }}" class="form-label">生效日期</label>
                    {{ contract_form.effective_date }}
                    {% if contract_form.effective_date.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.effective_date.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ contract_form.start_date.id_for_label }}" class="form-label required-field">开始日期</label>
                    {{ contract_form.start_date }}
                    {% if contract_form.start_date.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.start_date.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ contract_form.end_date.id_for_label }}" class="form-label required-field">到期日期</label>
                    {{ contract_form.end_date }}
                    {% if contract_form.end_date.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.end_date.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-12">
                <div class="mb-3">
                    <label for="{{ contract_form.amount.id_for_label }}" class="form-label required-field">合同金额</label>
                    <div class="input-group">
                        <span class="input-group-text">¥</span>
                        {{ contract_form.amount }}
                        {% if contract_form.amount.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.amount.errors %}{{ error }}{% endfor %}</div>{% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 合同双方信息 -->
    <div class="form-section">
        <h5><i class="fas fa-handshake me-2"></i>合同双方信息</h5>
        <div class="row">
            <div class="col-md-6">
                <h6 class="text-primary mb-3">我方信息</h6>
                <div class="mb-3">
                    <label for="{{ contract_form.our_company_name.id_for_label }}" class="form-label">公司名称</label>
                    {{ contract_form.our_company_name }}
                    {% if contract_form.our_company_name.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.our_company_name.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
                <div class="mb-3">
                    <label for="{{ contract_form.our_company_address.id_for_label }}" class="form-label">公司地址</label>
                    {{ contract_form.our_company_address }}
                    {% if contract_form.our_company_address.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.our_company_address.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="{{ contract_form.our_signatory.id_for_label }}" class="form-label">签约人</label>
                            {{ contract_form.our_signatory }}
                            {% if contract_form.our_signatory.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.our_signatory.errors %}{{ error }}{% endfor %}</div>{% endif %}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="{{ contract_form.our_signatory_title.id_for_label }}" class="form-label">签约人职务</label>
                            {{ contract_form.our_signatory_title }}
                            {% if contract_form.our_signatory_title.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.our_signatory_title.errors %}{{ error }}{% endfor %}</div>{% endif %}
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <h6 class="text-info mb-3">对方信息</h6>
                <div class="mb-3">
                    <label for="{{ contract_form.their_company_name.id_for_label }}" class="form-label">公司名称</label>
                    {{ contract_form.their_company_name }}
                    {% if contract_form.their_company_name.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.their_company_name.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
                <div class="mb-3">
                    <label for="{{ contract_form.their_company_address.id_for_label }}" class="form-label">公司地址</label>
                    {{ contract_form.their_company_address }}
                    {% if contract_form.their_company_address.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.their_company_address.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="{{ contract_form.their_signatory.id_for_label }}" class="form-label">签约人</label>
                            {{ contract_form.their_signatory }}
                            {% if contract_form.their_signatory.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.their_signatory.errors %}{{ error }}{% endfor %}</div>{% endif %}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="{{ contract_form.their_signatory_title.id_for_label }}" class="form-label">签约人职务</label>
                            {{ contract_form.their_signatory_title }}
                            {% if contract_form.their_signatory_title.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.their_signatory_title.errors %}{{ error }}{% endfor %}</div>{% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 合同条款摘要 -->
    <div class="form-section">
        <h5><i class="fas fa-file-alt me-2"></i>合同条款摘要</h5>
        <div class="mb-3">
            <label for="{{ contract_form.main_subject.id_for_label }}" class="form-label">主要标的物</label>
            {{ contract_form.main_subject }}
            {% if contract_form.main_subject.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.main_subject.errors %}{{ error }}{% endfor %}</div>{% endif %}
        </div>
        <div class="mb-3">
            <label for="{{ contract_form.delivery_requirements.id_for_label }}" class="form-label">交付要求</label>
            {{ contract_form.delivery_requirements }}
            {% if contract_form.delivery_requirements.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.delivery_requirements.errors %}{{ error }}{% endfor %}</div>{% endif %}
        </div>
        <div class="mb-3">
            <label for="{{ contract_form.special_terms.id_for_label }}" class="form-label">特殊条款</label>
            {{ contract_form.special_terms }}
            {% if contract_form.special_terms.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.special_terms.errors %}{{ error }}{% endfor %}</div>{% endif %}
        </div>
        <div class="mb-3">
            <label for="{{ contract_form.description.id_for_label }}" class="form-label">合同描述</label>
            {{ contract_form.description }}
            {% if contract_form.description.errors %}<div class="invalid-feedback d-block">{% for error in contract_form.description.errors %}{{ error }}{% endfor %}</div>{% endif %}
        </div>
    </div>
    
    <!-- 文件管理功能 -->
    <div class="form-section">
        <h5><i class="fas fa-file-upload me-2"></i>文件管理</h5>
        {{ contract_file_formset.management_form }}
        <div id="contract-file-form-container">
            {% for form in contract_file_formset %}
            <div class="file-item mt-3 contract-file-form-row {% if form.instance.pk %}existing-file{% else %}new-file{% endif %}" id="contract-file-form-{{ forloop.counter0 }}">
                <div class="file-info">
                    <i class="fas fa-file-alt file-icon text-info"></i> {# Generic file icon, can be improved with JS #}
                    <div class="file-details">
                        <h6>{{ form.file_name.value|default:"新文件" }}</h6>
                        <small>{% if form.instance.file_path %}{{ form.instance.file_path.name }}{% else %}选择文件{% endif %}</small>
                    </div>
                </div>
                <div class="d-flex align-items-center">
                    <div class="me-2">
                        <div class="mb-2">
                            <label for="{{ form.file_type.id_for_label }}" class="form-label">文件类型</label>
                            {{ form.file_type }}
                        </div>
                        <div class="mb-2">
                            <label for="{{ form.file_name.id_for_label }}" class="form-label">文件名称</label>
                            {{ form.file_name }}
                        </div>
                        <div class="mb-2">
                            <label for="{{ form.file_path.id_for_label }}" class="form-label">文件路径</label>
                            {{ form.file_path }}
                        </div>
                        <div class="mb-2">
                            <label for="{{ form.description.id_for_label }}" class="form-label">文件描述</label>
                            {{ form.description }}
                        </div>
                        {% if form.instance.pk %}{{ form.id }}{% endif %}
                    </div>
                    {% if form.instance.pk %}
                    <a href="{{ form.instance.file_path.url }}" target="_blank" class="btn btn-sm btn-outline-primary me-2">
                        <i class="fas fa-eye"></i> 查看
                    </a>
                    {% endif %}
                    <button type="button" class="btn-remove-file remove-contract-file-button">
                        <i class="fas fa-trash"></i>
                    </button>
                    {{ form.DELETE }}
                </div>
                {% if form.errors %}
                    <div class="invalid-feedback d-block">
                        {% for field_error in form.errors.values %}
                            {% for error in field_error %}{{ error }}{% endfor %}
                        {% endfor %}
                    </div>
                {% endif %}
            </div>
            {% endfor %}
        </div>
        <button type="button" class="btn btn-outline-success mt-3" id="add-contract-file-button">
            <i class="fas fa-plus me-2"></i>添加更多文件
        </button>
    </div>
    
    <!-- 合同流程管理 -->
    {% if contract %}
    <div class="form-section">
        <h5><i class="fas fa-tasks me-2"></i>合同流程管理</h5>
        
        <!-- 当前状态显示 -->
        <div class="mb-4">
            <label class="form-label">当前状态</label>
            <div class="status-badge {% if contract.status == 'draft' %}status-draft{% elif contract.status == 'active' %}status-active{% endif %}">
                {% if contract.status == 'draft' %}
                    <i class="fas fa-edit me-2"></i>草稿状态
                {% elif contract.status == 'active' %}
                    <i class="fas fa-check me-2"></i>合同生效中
                {% elif contract.status == 'expired' %}
                    <i class="fas fa-clock me-2"></i>合同已过期
                {% elif contract.status == 'terminated' %}
                    <i class="fas fa-times me-2"></i>合同已终止
                {% endif %}
            </div>
            
            {% if contract.status == 'draft' %}
            <div class="mt-3">
                <button type="button" class="btn btn-primary" onclick="submitForReview()">
                    <i class="fas fa-paper-plane me-2"></i>提交审核
                </button>
                <button type="button" class="btn btn-outline-secondary ms-2" onclick="printContract()">
                    <i class="fas fa-print me-2"></i>打印合同
                </button>
            </div>
            {% endif %}
        </div>
        
        <!-- 审核记录展示区域 -->
        {% if contract.reviews.all %}
        <div class="mb-4">
            <label class="form-label">审核记录</label>
            <div class="review-timeline">
                {% for review in contract.reviews.all %}
                <div class="review-item">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-1">{{ review.get_review_type_display }}</h6>
                            <p class="mb-1">{{ review.review_notes|default:"无备注" }}</p>
                            <small class="text-muted">
                                <i class="fas fa-user me-1"></i>{{ review.reviewer.get_full_name|default:review.reviewer.username }}
                                <i class="fas fa-clock ms-2 me-1"></i>{{ review.created_at|date:"Y-m-d H:i" }}
                            </small>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
        {% endif %}
    </div>
    {% endif %}
    
    <!-- 提交按钮 -->
    <div class="form-section">
        <div class="d-flex justify-content-between">
            <div>
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="fas fa-save me-2"></i>{% if contract %}更新合同{% else %}创建合同{% endif %}
                </button>
                <button type="button" class="btn btn-outline-secondary btn-lg ms-2" onclick="resetForm()">
                    <i class="fas fa-undo me-2"></i>重置
                </button>
            </div>
            <div>
                <a href="{% url 'assets:contract_list' %}" class="btn btn-outline-danger btn-lg">
                    <i class="fas fa-times me-2"></i>取消
                </a>
            </div>
        </div>
    </div>
</form>
    </div>
</div>

<script>
// Page load initialization
document.addEventListener('DOMContentLoaded', function() {
    initializeContractFileFormset();
    initializeFormValidation();
    initializeSupplierSelection();
});

// Initialize formset for dynamic contract file forms
function initializeContractFileFormset() {
    const formContainer = document.getElementById('contract-file-form-container');
    const addButton = document.getElementById('add-contract-file-button');
    let totalForms = document.querySelector('#id_contract_files-TOTAL_FORMS');

    addButton.addEventListener('click', function() {
        const currentForms = document.querySelectorAll('.contract-file-form-row').length;
        const newForm = formContainer.children[0].cloneNode(true); // Clone the first form as a template

        // Clear values and update names/ids for new form
        newForm.querySelectorAll('input, textarea, select').forEach(input => {
            const name = input.name.replace(/-\d+-/, `-${currentForms}-`);
            const id = input.id.replace(/-\d+-/, `-${currentForms}-`);
            input.name = name;
            input.id = id;
            input.value = ''; // Clear value for new form
            if (input.type === 'checkbox') {
                input.checked = false;
            }
        });
        newForm.id = `contract-file-form-${currentForms}`;
        newForm.classList.remove('existing-file');
        newForm.classList.add('new-file');
        newForm.style.display = 'block'; // Ensure it's visible

        // Update DELETE checkbox for new form
        const deleteCheckbox = newForm.querySelector('input[type="checkbox"][name$="-DELETE"]');
        if (deleteCheckbox) {
            deleteCheckbox.checked = false;
        }

        formContainer.appendChild(newForm);
        totalForms.value = parseInt(totalForms.value) + 1;

        // Re-attach event listeners for new form's remove button
        newForm.querySelector('.remove-contract-file-button').addEventListener('click', function() {
            removeContractFileForm(newForm);
        });
    });

    // Attach event listeners for existing remove buttons
    document.querySelectorAll('.remove-contract-file-button').forEach(button => {
        button.addEventListener('click', function() {
            const formRow = this.closest('.contract-file-form-row');
            removeContractFileForm(formRow);
        });
    });
}

function removeContractFileForm(formRow) {
    const deleteCheckbox = formRow.querySelector('input[type="checkbox"][name$="-DELETE"]');
    if (deleteCheckbox) {
        deleteCheckbox.checked = true;
        formRow.style.display = 'none'; // Hide the form row
    } else {
        formRow.remove(); // For newly added forms without a DELETE checkbox
    }
}

// Initialize supplier selection (keep as is)
function initializeSupplierSelection() {
    const supplierSelect = document.getElementById('id_supplier'); // Use id_supplier for Django form field
    
    supplierSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        
        if (this.value) {
            // 自动填充对方公司信息
            document.getElementById('id_their_company_name').value = selectedOption.text; // Use id_their_company_name
            if (selectedOption.dataset.contact) {
                document.getElementById('id_their_signatory').value = selectedOption.dataset.contact; // Use id_their_signatory
            }
        }
    });
}

// Initialize form validation (keep as is, adapted for Django forms)
function initializeFormValidation() {
    const form = document.getElementById('contractForm');
    const startDateInput = document.getElementById('id_start_date'); // Use id_start_date
    const endDateInput = document.getElementById('id_end_date');     // Use id_end_date
    const signedDateInput = document.getElementById('id_signed_date'); // Use id_signed_date
    const effectiveDateInput = document.getElementById('id_effective_date'); // Use id_effective_date
    
    // 日期验证
    function validateDates() {
        const signedDate = signedDateInput ? new Date(signedDateInput.value) : null;
        const effectiveDate = effectiveDateInput ? new Date(effectiveDateInput.value) : null;
        const startDate = new Date(startDateInput.value);
        const endDate = new Date(endDateInput.value);

        // Clear previous custom validity messages
        startDateInput.setCustomValidity('');
        endDateInput.setCustomValidity('');
        if (signedDateInput) signedDateInput.setCustomValidity('');
        if (effectiveDateInput) effectiveDateInput.setCustomValidity('');

        let isValid = true;

        if (startDate && endDate && startDate >= endDate) {
            endDateInput.setCustomValidity('结束日期必须晚于开始日期');
            isValid = false;
        }
        
        if (signedDate && effectiveDate && signedDate > effectiveDate) {
            effectiveDateInput.setCustomValidity('生效日期不能早于签订日期');
            isValid = false;
        }
        
        if (effectiveDate && startDate && effectiveDate > startDate) {
            startDateInput.setCustomValidity('开始日期不能早于生效日期');
            isValid = false;
        }
        
        return isValid;
    }
    
    if (signedDateInput) signedDateInput.addEventListener('change', validateDates);
    if (effectiveDateInput) effectiveDateInput.addEventListener('change', validateDates);
    startDateInput.addEventListener('change', validateDates);
    endDateInput.addEventListener('change', validateDates);
    
    // 表单提交验证
    form.addEventListener('submit', function(e) {
        if (!validateDates()) {
            e.preventDefault();
            e.stopPropagation();
            alert('请检查日期设置');
            return;
        }
        // Django forms handle most other validation.
    });
}

// Reset form (needs adaptation for formsets)
function resetForm() {
    if (confirm('确定要重置表单吗？所有未保存的数据将丢失。')) {
        document.getElementById('contractForm').reset();
        // Reset formset forms
        const formContainer = document.getElementById('contract-file-form-container');
        while (formContainer.children.length > 1) { // Keep one empty form for new entries
            formContainer.removeChild(formContainer.lastChild);
        }
        const firstForm = formContainer.children[0];
        firstForm.querySelectorAll('input, textarea, select').forEach(input => {
            input.value = '';
            if (input.type === 'checkbox') {
                input.checked = false;
            }
        });
        document.querySelector('#id_contract_files-TOTAL_FORMS').value = 1; // Reset total forms

        // Re-show hidden deleted forms if any
        document.querySelectorAll('.contract-file-form-row[style*="display: none"]').forEach(row => {
            row.style.display = 'block';
            const deleteCheckbox = row.querySelector('input[type="checkbox"][name$="-DELETE"]');
            if (deleteCheckbox) {
                deleteCheckbox.checked = false;
            }
        });
    }
}

// 提交审核
function submitForReview() {
    if (confirm('确定要提交合同进行审核吗？')) {
        // 这里可以添加提交审核的逻辑
        alert('审核提交功能正在开发中');
    }
}

// 打印合同
function printContract() {
    window.print();
}
</script>
{% endblock %}